<?php
class main{
        protected static $urlVars;
	protected static $microtimeStart;
	protected static $configs;
	protected static $currentModule;
	protected static $currentModuleUrlName;
	protected static $currentModuleBddPrefix;
	
	//Admin
	private static $admin = false;
	private static $isAJAX = false;
	
	//Smarty
	protected static $smarty;
	
	public function __construct($microtime){
		//Temps de generation de page
		self::setMicrotime($microtime);
		
		//Configs
		self::setConfigs();
		
		//Capture des arguments
		self::setUrlVars();
		
		//Determine if its an admin call
		self::setIfAdmin();
		
		//Initialization des extensions du noyau
		error::init();//Gestion erreurs
		dao::init();//Objet d'Acces aux Données (BDD)
		lang::init();//Gestion de l'internationalization
		
		//Recherche et instanciation du module concerné
		self::getModule();
		
		//Ajout de Smarty si demandé
		if(self::getConfig('smarty') && !self::$admin){
			includeClass(self::getConfig('site_directory').'lib/smarty/libs/Smarty.class.php');
			self::$smarty = new Smarty();
			self::configSmarty();
			
			//Activer ou pas le debug
			if(self::getConfig('debug_smarty'))
				main::debugSmarty();
		}
		//Appel a la génération de la page
		self::getPage();
	}

	//***************************
	// CONFIGS/URL REWRITING
	//***************************
	
	
	//URL vars
        private static function setUrlVars(){
		$_SESSION['last_page'] = $_SESSION['current_page'];
		if(preg_match('#https\://#',self::getConfig('site_url')))
			$url = 'https://'.$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'];
		else
			$url = 'http://'.$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'];
		
		$url_base = self::getConfig('site_url');
		$url_base = preg_replace('#\.#','\.',$url_base);
		$url = preg_replace('#'.$url_base.'#','',$url);
		$url = preg_replace('#\.html|\.htm|/$#','',$url);
		$url_explode = explode("/",$url);
		array_shift($url_explode);
		self::$urlVars = $url_explode;
		$_SESSION['current_page'] = $url_explode;
		return $url_explode;
        }

        protected static function getUrlVar($number){
		if(self::$admin)
			$return = strtolower(self::$urlVars[$number]);
		else
			$return = strtolower(self::$urlVars[$number-1]);
		return $return;
        }
	
	protected static function restoreLastUrlVars(){
		$_SESSION['current_page'] = $_SESSION['last_page'];
		self::$urlVars = $_SESSION['last_page'];
		
		return self::$urlVars;
	}
	
	//Configs
	private function setConfigs(){
		//Lecture du config file
		$config_file = file_get_contents('../conf/config.php');
		$config_file = str_replace("\r\n", "\n", $config_file);
		$config_file = explode("\n", $config_file);
		
		//Ajout des configs en tableaux accessible dans l'objet
		foreach($config_file as $ligne){
			if(trim($ligne) != ""){
				if((!preg_match('#^\\\\#',$ligne))&&(preg_match('#:#',$ligne))){
					$arg=explode(':',$ligne);
					if($arg[0] == "site_url")
						self::$configs[$arg[0]] = $arg[1].':'.$arg[2];
					else
						self::$configs[$arg[0]] = $arg[1];
				}
			}
		}
	}
	
	protected static function getConfig($var){
            return self::$configs[$var];
	}
	
	protected static function getConfigs(){
            return self::$configs;
	}
	
	protected static function setIfAdmin(){
		if(self::getUrlVar(1) == self::getConfig('admin_path'))
			self::$admin=true;//On décale les URLVars de 1 vers la gauche
	}

        protected static function getServerVar($var){
            return $_SERVER[$var];
	}
	
	//Post var

        protected static function getPost($postvar, $htmlentities=true){
            // A voir après pour la sécurisation.
            return htmlentities($_POST[$postvar]);
        }
	
	//Microtime

	private static function setMicrotime($var){
		self::$microtimeStart = $var;
	}
	
	//***************************
	// MODULES
	//***************************
	protected static function getModule(){
		if(self::$admin){
			if(isset($_SESSION['admin_auth'])){
				if(self::getUrlVar(1) == ""){
					$module = modules::getDefaultModule(true);
				}else{
					$module = modules::searchModule(self::getUrlVar(1));
				}
				
				if(count($module)){
					if(!includeClass(self::getConfig('site_directory')."modules/".$module['urlname']."/admin/".$module['urlname'].".class.php")){
						die(error::show("core1",__FILE__,((__LINE__)-1),"file : ".self::getConfig('site_directory')."modules/".$module['urlname']."/admin/".$module['urlname'].".class.php"));
					}else{
						modules::addModuleInfos($module);
						self::$currentModuleUrlName = $module['urlname'];
						self::$currentModuleBddPrefix = $module['prefix'];
						self::$currentModule = new $module['urlname'];
					}
				}
			}
			
			//On inclut les modules ADMIN
			includeClass(self::getConfig('site_directory')."class/admin/admin_users.class.php");
			includeClass(self::getConfig('site_directory')."class/admin/admin_menus.class.php");
                        includeClass(self::getConfig('site_directory')."class/admin/admin_desktop.class.php");
		}else{
			if(self::getUrlVar(1) == "" || self::getConfig('unique_module')){
				$module = modules::getDefaultModule(false);
			}else{
				$module = modules::searchModule(self::getUrlVar(1));
			}
			
			if(!$module){
				//On lance l'admin sans module
				
				//On définis que finalement on est en admin
				self::$admin = true;
				
				//On inclut les modules ADMIN
				includeClass(self::getConfig('site_directory')."class/admin/admin_users.class.php");
				includeClass(self::getConfig('site_directory')."class/admin/admin_menus.class.php");
				includeClass(self::getConfig('site_directory')."class/admin/admin_desktop.class.php");
				
				//die(error::show("core2",__FILE__,((__LINE__)-8),"no module"));
			}else{
				if(!includeClass(self::getConfig('site_directory')."modules/".$module['urlname']."/".$module['urlname'].".class.php")){
					die(error::show("core1",__FILE__,((__LINE__)-1),"file : ".self::getConfig('site_directory')."modules/".$module['urlname']."/".$module['urlname'].".class.php"));
				}else{
					modules::addModuleInfos($module);
					self::$currentModuleUrlName = $module['urlname'];
					self::$currentModuleBddPrefix = $module['prefix'];
					self::$currentModule = new $module['urlname'];
				}
			}
		}
	}
	
	//***************************
	// SMARTY
	//***************************
	
	private function configSmarty(){
		if(self::$admin){
			self::$smarty->compile_dir = self::getConfig('site_directory')."lib/smarty/templates_c/admin";
			self::$smarty->cache_dir = self::getConfig('site_directory')."lib/smarty/cache/admin";
			self::$smarty->config_dir = self::getConfig('site_directory')."lib/smarty/configs";
			self::$smarty->template_dir = self::getConfig('site_directory')."templates/".self::$currentModuleUrlName."/admin";
		}else{
			self::$smarty->compile_dir = self::getConfig('site_directory')."lib/smarty/templates_c";
			self::$smarty->cache_dir = self::getConfig('site_directory')."lib/smarty/cache";
			self::$smarty->config_dir = self::getConfig('site_directory')."lib/smarty/configs";
			self::$smarty->template_dir = self::getConfig('site_directory')."templates/".self::$currentModuleUrlName;
		}
	}
	
	private function debugSmarty(){
		self::$smarty->debugging = true;
		self::$smarty->debug_tpl = self::getConfig('site_directory')."lib/smarty/libs/debug.tpl";
	}
	
	
	//***************************
	// ADMIN
	//***************************
	
	
	//Tags
	private static function getAdminTags(){
		//Hooks
		if(!$_SESSION['admin_auth'])
			$tags['LOGIN_ERROR'] = admin_users::hookLogin();
		
		if(!$_SESSION['admin_auth']){
			$tags['BLOCK_MENU_LANG'] = lang::getFormLang("buttons");
			$tags = common::tags_merge($tags, admin_users::getLoginTags());
		}else{
                        $tags['BLOCK_MENU_ACCOUNT'] = admin_users::getMenuAccount();
			$tags['BLOCK_MENU_OPTIONS'] = admin_users::getMenuOptions();
                        $tags['BLOCK_MENU'] = admin_menus::createMenus();
			$tags['BLOCK_SUB_MENU'] = admin_menus::createSubMenus();
			$tags['BLOCK_MENU_LANG'] = lang::getFormLang("system");
			
			if(self::getUrlVar(1) != "" && self::getUrlVar(1) == self::$currentModuleUrlName){
                                $modTags = main::$currentModule->getTags();
				$tags = common::tags_merge($tags, $modTags);
			}else{
				switch(self::getUrlVar(1)){
                                        //Déco
                                        case "disconnect":
                                                admin_users::disconnect();
                                                header('location: '.self::getConfig('site_url').self::getConfig('admin_path').".html");
                                                die();
                                                break;
                                        
                                        
					default:
					case "desktop":
						$tags['page_title'] = "Bureau";
                                                $tags['BLOCK_CONTENT'] = admin_desktop::getDesktop();
                                                
						if(modules::getModuleInfo(self::$currentModuleUrlName,'desktop') && is_object(self::$currentModule)){
                                                        $tags['BLOCK_CONTENT'] .= self::$currentModule->getDesktop();
                                                }
						break;
					
					case "modules":
						
						break;
					
					case "users":
						
						break;
				}
			}
			
			//génération du menu
			
		}
		
		$tags['page'] = self::getCommonTags();
		$tags['lang'] = lang::getTags();
		$tags['site_title'] = self::getConfig('site_name');
		$tags['javascript'] .= "<script type='text/javascript'>var admin_directory = '".self::getConfig('admin_path')."';</script>";
		$tags['javascript'] .= lang::show_JS_all();
		
		return $tags;
	}
	
	protected static function getCommonTags(){
		if(self::getConfig('smarty') && !self::$admin){
			self::$smarty->assign('nb_request',dao::getNbQueries());
			self::$smarty->assign('generate_time',round((microtime(true) - self::$microtimeStart)*1000 , 0)."ms");
		}else{
			$Tags = array();
			$Tags['site_url'] = self::getConfig('site_url');
			$Tags['admin_directory'] = self::getConfig('admin_path');
			$Tags['nb_q'] = dao::getNbQueries();
			$Tags['tps_ms'] = round((microtime(true) - self::$microtimeStart)*1000 , 0);
			$Tags['favicon'] = '<link rel="icon" type="image/png" href="'.self::getConfig('site_url').'system/img/favicon.png" />';
			
			//Get Custom Configs
			$sql = "SELECT config, value FROM wfs_configs WHERE 1";
			$result = dao::request_assoc($sql);
			
			if($result){
			    foreach($result as $config){
				$Tags[$config['config']] = $config['value'];
			    }
			}
		}
		
		return $Tags;
	}
	
	//templates
	protected static function setAjaxContent(){
		error::setNoErrorPage();//pas de page d'erreur en ajax, ca serait moche
		self::$isAJAX = true;
	}
	
	private static function getAdminTemplate(){
		if(!isset($_SESSION['admin']['user']))
			return common::getContent(self::getConfig('site_directory').'templates/system/connection.tpl');
		else{
			if(self::$isAJAX){
				return common::getContent(self::getConfig('site_directory').'templates/system/ajax.tpl');
				self::restoreLastUrlVars();
			}else
				return common::getContent(self::getConfig('site_directory').'templates/system/content.tpl');
		}
	}
	
	//***************************
	// PAGE GENERATOR
	//***************************
	
	protected static function getTags(){
		if(self::$admin){
			return self::getAdminTags();
		}else{
			return self::$currentModule->getTags();
		}
	}
	
	protected static function getTemplates(){
		if(self::$admin){
			return self::getAdminTemplate();
		}else{
			return self::$currentModule->getTemplate();
		}
	}
	
	private static function getPage(){
		$tags = self::getTags();
		$template = self::getTemplates();
		if(self::getConfig('smarty') && !self::$admin){
			
			self::getCommonTags();
			self::$smarty->display("layout.tpl");
		}else{
			echo common::mergeTagsTemplate($template, $tags);
		}
	}
}

//On apelle l'extension lang.
require_once("../class/lang.class.php");
//On apelle l'extension error.
require_once("../class/error.class.php");
//On apelle l'extension dao.
require_once("../class/dao.class.php");
//On apelle l'extension common.
require_once("../class/common.class.php");
//On apelle l'extension modules.
require_once("../class/modules.class.php");
?>